package com.oracle.third.service.email.listener.service;

import com.oracle.third.utils.CodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class EmailService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${cache_key_prefix}")
    private String cachePrefix;
    @Value("${email.username}")
    private String fromAddress;
    @Value("${email.subject}")
    private String emailSubject;

    /**
     * 发送验证码到，指定的email上
     * @param email
     */
    public void sendEmailRandom(String email) {
        String maileToAddress = email;// 目标邮箱地址
        String subject = emailSubject;// 邮件标题
        String message = CodeUtils.createCode();// 邮件内容正文
        System.out.println("To: " + maileToAddress);
        System.out.println("Subject: " + subject);
        System.out.println("Message: " + message);

        // 邮件对象
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(fromAddress);// 源发送地址
        simpleMailMessage.setTo(maileToAddress);// 目标地址
        simpleMailMessage.setSubject(subject);//发送的邮件标题
        simpleMailMessage.setText(message);//发送的邮件内容
        javaMailSender.send(simpleMailMessage);// 执行发送

        //把验证码保存到Redis缓存中
        String cacheKey = this.cachePrefix+"email:"+email;
        this.redisTemplate.opsForValue().set(cacheKey,message,3,TimeUnit.MINUTES);
        //保存一个可以重新发送邮件的时间
        String reSendKey = this.cachePrefix+"reSendEmail:"+email;
        this.redisTemplate.opsForValue().set(reSendKey,"re send email",1,TimeUnit.MINUTES);
    }


}
